package com.etooling.framework.service.impl;

import com.alibaba.fastjson.JSON;
import com.etooling.framework.entity.AttachFile;
import com.etooling.framework.entity.FileResource;
import com.etooling.framework.repository.AttachFileRepository;
import com.etooling.framework.service.FileUploadSaveService;
import com.etooling.framework.utils.DateFm;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @author X
 * @title: FileUploadSaveServiceImpl
 * @projectName irobot_jjb
 * @description: 上传到应用服务器的应用
 * @date 2020/12/2917:39
 */
public class FileUploadToQiNiuServiceImpl implements FileUploadSaveService {

    @Override
    public AttachFile upload(AttachFileRepository attachFileRepository, MultipartFile uploadFile, FileResource fileResource, Boolean isEncrypt) throws Exception {

        //初始化七牛参数
        Configuration cfg = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(cfg);
        String accessKey = fileResource.getAccessKey();
        String secretKey = fileResource.getSecretKey();
        String bucket = fileResource.getBucket();
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);


        //根据规则生成对应的文件名（含目录）

        AttachFile attachFile = new AttachFile();
        attachFile.setEncrypt(isEncrypt);
        //原来的文件名
        String origName = uploadFile.getOriginalFilename();
        String fileType = origName.substring(origName.lastIndexOf("."));
        origName = origName.split(" ")[0];
        //为了文件的安全进行重命名
        String newFileName = UUID.randomUUID().toString() + fileType;
        //拿出服务器存放目录
        attachFile.setName(origName);
        attachFile.setFileType(fileType);
        attachFile.setFileResource(fileResource);
        String dataFileRootDir = fileResource.getBucket();
        String fileDir = DateFm.to_char(new Date(), "yyyyMMdd");
        //处理相对路径
        String absName = fileDir + "/" + newFileName;
        //加上日期和根目录的绝对路径
        String filePath = dataFileRootDir + "/" + absName;
        attachFile.setFilePath(filePath);
        Response response = uploadManager.put(uploadFile.getInputStream(), filePath, upToken, null, null);
        DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
        String webPath = fileResource.getBasePath() + "/" + filePath;
        attachFile.setFilePath(absName);
        attachFile.setCreateTime(new Date());
        attachFile.setWebPath(webPath);
        attachFileRepository.save(attachFile);
        return attachFile;
    }

    @Override
    public AttachFile upload(AttachFileRepository attachFileRepository, MultipartFile uploadFile, FileResource fileResource, Boolean isEncrypt, Map<String, String> limitMap) throws Exception {

        //原来的文件名
        String origName = uploadFile.getOriginalFilename();

        String fileType = origName.substring(origName.lastIndexOf("."));
        origName = origName.split(" ")[0];
        if (limitMap.get(origName) != null) {
            //初始化七牛参数
            Configuration cfg = new Configuration(Region.huanan());
            UploadManager uploadManager = new UploadManager(cfg);
            String accessKey = fileResource.getAccessKey();
            String secretKey = fileResource.getSecretKey();
            String bucket = fileResource.getBucket();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);


            //根据规则生成对应的文件名（含目录）

            AttachFile attachFile = new AttachFile();
            attachFile.setEncrypt(isEncrypt);


            //为了文件的安全进行重命名
            String newFileName = UUID.randomUUID().toString() + fileType;
            //拿出服务器存放目录
            attachFile.setName(origName);
            attachFile.setFileType(fileType);
            attachFile.setFileResource(fileResource);
            String dataFileRootDir = fileResource.getBucket();
            String fileDir = DateFm.to_char(new Date(), "yyyyMMdd");
            //处理相对路径
            String absName = fileDir + "/" + newFileName;
            //加上日期和根目录的绝对路径
            String filePath = dataFileRootDir + "/" + absName;
            attachFile.setFilePath(filePath);
            Response response = uploadManager.put(uploadFile.getInputStream(), filePath, upToken, null, null);
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            String webPath = fileResource.getBasePath() + "/" + filePath;
            attachFile.setFilePath(absName);
            attachFile.setCreateTime(new Date());
            attachFile.setWebPath(webPath);
            System.out.println(attachFile.toString());
            attachFileRepository.save(attachFile);
            return attachFile;
        } else {
            return null;
        }

    }

    @Override
    public AttachFile uploadByte(AttachFileRepository attachFileRepository, String origName, byte[] image, FileResource fileResource, Boolean isEncrypt) throws Exception {
        //初始化七牛参数
        Configuration cfg = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(cfg);
        String accessKey = fileResource.getAccessKey();
        String secretKey = fileResource.getSecretKey();
        String bucket = fileResource.getBucket();
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);


        //根据规则生成对应的文件名（含目录）

        AttachFile attachFile = new AttachFile();
        attachFile.setEncrypt(isEncrypt);
        //原来的文件名
        String fileType = origName.substring(origName.lastIndexOf("."));
        origName = origName.split(" ")[0];
        //为了文件的安全进行重命名
        String newFileName = UUID.randomUUID().toString() + fileType;
        //拿出服务器存放目录
        attachFile.setName(origName);
        attachFile.setFileType(fileType);
        attachFile.setFileResource(fileResource);
        String dataFileRootDir = fileResource.getBucket();
        String fileDir = DateFm.to_char(new Date(), "yyyyMMdd");
        //处理相对路径
        String absName = fileDir + "/" + newFileName;
        //加上日期和根目录的绝对路径
        String filePath = dataFileRootDir + "/" + absName;
        attachFile.setFilePath(filePath);
        Response response = uploadManager.put(image, filePath, upToken);
        DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
        String webPath = fileResource.getBasePath() + "/" + filePath;
        attachFile.setFilePath(absName);
        attachFile.setCreateTime(new Date());
        attachFile.setWebPath(webPath);
        attachFileRepository.save(attachFile);
        return attachFile;
    }

    @Override
    public AttachFile uploadXinDi(AttachFileRepository attachFileRepository, MultipartFile uploadFile, FileResource fileResource, Boolean isEncrypt) throws Exception {
        //初始化七牛参数
        Configuration cfg = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(cfg);
        String accessKey = fileResource.getAccessKey();
        String secretKey = fileResource.getSecretKey();
        String bucket = fileResource.getBucket();
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);


        //根据规则生成对应的文件名（含目录）

        AttachFile attachFile = new AttachFile();
        attachFile.setEncrypt(isEncrypt);
        //原来的文件名
        String origName = uploadFile.getOriginalFilename();
        String fileType = origName.substring(origName.lastIndexOf("."));
        origName = origName.split("\\.")[0];
        //为了文件的安全进行重命名
        String newFileName = UUID.randomUUID().toString() + fileType;
        //拿出服务器存放目录
        attachFile.setName(origName);
        attachFile.setFileType(fileType);
        attachFile.setFileResource(fileResource);
        String dataFileRootDir = fileResource.getBucket();
        String fileDir = DateFm.to_char(new Date(), "yyyyMMdd");
        //处理相对路径
        String absName = fileDir + "/" + newFileName;
        //加上日期和根目录的绝对路径
        String filePath = dataFileRootDir + "/" + absName;
        attachFile.setFilePath(filePath);
        Response response = uploadManager.put(uploadFile.getInputStream(), filePath, upToken, null, null);
        DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
        String webPath = fileResource.getBasePath() + "/" + filePath;
        attachFile.setFilePath(absName);
        attachFile.setCreateTime(new Date());
        attachFile.setWebPath(webPath);
        attachFileRepository.save(attachFile);
        return attachFile;
    }


}
